import { Body, Controller, Post, UseGuards } from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { WxLoginService } from '../services/wxLogin.services';
import { WxLoginDTO } from '../dto/wxLogin.dto';
import { ResponseUtils } from 'src/common/utils/response.utils';
import { UserService } from '../services/user.service';
import { plainToInstance } from 'class-transformer';
import { User } from '../entities/user.entity';
import { WxUtils } from 'src/common/utils/wx.utils';
import { AuthService } from 'src/common/auth/auth.service';

@Controller('api/login')
@ApiTags('微信-登录')
export class WxLoginController {
  constructor(
    private readonly wxLoginService: WxLoginService,
    private readonly userService: UserService,
    private readonly authService: AuthService,
  ) {}

  @Post()
  @ApiOperation({ summary: '登录', description: '通过微信参数获取用户token' })
  async getWxLoginUrl(@Body() wxLoginDTO: WxLoginDTO): Promise<any> {
    // 查看code是否正确
    const result = await WxUtils.getOpenIdByParams({
      js_code: wxLoginDTO.code,
      appid: wxLoginDTO.appid,
      secret: wxLoginDTO.secret,
      grant_type: 'authorization_code',
    });

    // code错误，返回具体信息
    if (result.errcode) {
      return ResponseUtils.error(result.errmsg);
    }
    // 查看当前用户的信息
    let user = await this.userService.findUserByOpenId(result.openid);

    // 没有用户，注册用户
    if (!user) {
      const registerUser = plainToInstance(User, {
        openId: result.openid,
      });

      user = await this.userService.registerUser(registerUser);
    }

    const token = await this.authService.generateString(user.userId);

    return ResponseUtils.success({
      token,
    });
  }
}
